package fon.rm2.client.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;


public class ClientThread extends Thread
{
	@SuppressWarnings("unused")
	private static final String TAG = "ClientThread";
	
	private SocketActivity parent = null;	

	private Socket s = null;
	private PrintWriter outputToServer = null;
	private BufferedReader inputFromServer = null;
	
	private String humanIpAddress = "";
	private int portNumber = 0;
	
	private boolean pauseMe = true;
	
	private String inData = "";
	public String currentMessage = "";
	
	
	public ClientThread(SocketActivity parent, String ipAddress, int port) throws UnknownHostException, IOException
	{
		this.parent = parent;
		this.humanIpAddress = ipAddress;
		this.portNumber = port;
		
		try
		{ 
			InetAddress serverAddr = InetAddress.getByName(this.humanIpAddress);
	        s = new Socket(serverAddr,this.portNumber);
	        outputToServer = new PrintWriter( new BufferedWriter( new OutputStreamWriter(s.getOutputStream())),true);
	        inputFromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
		} catch (UnknownHostException e) {
			throw e;
		} catch (IOException e) {
			throw e;
		}		
	}
	
	public void SendMessageToServer(String message)
	{
		if(outputToServer != null)
			outputToServer.println(message);
	}
	
	@Override
	public void run() {

		try
		{			
			while(!parent.stopClientThread)
			{					
				synchronized(this) 
				{
					while(this.pauseMe) 
					{
						wait();
					}
				}
				
				inData = inputFromServer.readLine();
				if(!inData.equals(""))
				{
					this.currentMessage = String.copyValueOf(inData.toCharArray(), 0, inData.length());
					parent.mHandler.post(parent.mUpdateUIFromClient);
				}
	        }
			s.close();
			outputToServer.close();
			inputFromServer.close();
			this.join();
		}
		catch (Exception ex)
		{ 
		}		
	}
	
	public synchronized void PauseClient() 
	{
		if(!pauseMe)
		{
			this.pauseMe = true;
			notifyAll();
		}
	}
	public synchronized void ResumeClient() 
	{
		if(pauseMe)
		{
			this.pauseMe = false;
			notifyAll();
		}
	}
}
